<template>
  <view class="detail-page">
    <!-- 帖子详情 -->
    <view v-if="post" class="post-detail">
      <!-- 用户信息 -->
      <view class="user-info">
        <image 
          :src="post.users.avatar_url || '/static/default-avatar.png'" 
          class="avatar"
        ></image>
        <view class="user-detail">
          <text class="nickname">{{ post.users.nickname || '用户' }}</text>
          <text class="time">{{ formatTime(post.created_at) }}</text>
        </view>
      </view>

      <!-- 帖子内容 -->
      <view class="content">
        <text>{{ post.content }}</text>
      </view>

      <!-- 图片展示 -->
      <view v-if="post.images && post.images.length > 0" class="images-grid">
        <image 
          v-for="(img, index) in post.images" 
          :key="index"
          :src="getFullImageUrl(img)"
          class="post-image"
          :class="getImageClass(post.images.length)"
          mode="aspectFill"
          @click="previewImage(post.images, index)"
        ></image>
      </view>

      <!-- 操作按钮 -->
      <view class="actions">
        <view class="action-item" @click="toggleLike">
          <text class="action-icon" :class="post.is_liked ? 'liked' : ''">❤️</text>
          <text class="count">{{ post.like_count || 0 }}</text>
        </view>
        <view class="action-item" @click="focusCommentInput">
          <text class="action-icon">💬</text>
          <text class="count">{{ post.comment_count || 0 }}</text>
        </view>
        <view class="action-item" @click="sharePost">
          <text class="action-icon">🔗</text>
          <text class="count">{{ post.share_count || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="comments-section">
      <view class="section-title">评论 ({{ post?.comment_count || 0 }})</view>
      
      <scroll-view 
        class="comment-list" 
        scroll-y="true"
        @scrolltolower="loadMoreComments"
      >
        <view 
          v-for="comment in commentList" 
          :key="comment.id"
          class="comment-item"
        >
          <image 
            :src="comment.users.avatar_url || '/static/default-avatar.png'" 
            class="comment-avatar"
          ></image>
          <view class="comment-content">
            <view class="comment-user">{{ comment.users.nickname || '用户' }}</view>
            <view class="comment-text">{{ comment.content }}</view>
            <view class="comment-time">{{ formatTime(comment.created_at) }}</view>
          </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading" v-if="commentLoading">
          <text>加载中...</text>
        </view>
        <view class="no-more" v-if="commentNoMore && commentList.length > 0">
          <text>没有更多评论了</text>
        </view>
        <view class="empty" v-if="!commentLoading && commentList.length === 0">
          <text>暂无评论，来发表第一条评论吧~</text>
        </view>
      </scroll-view>
    </view>

    <!-- 评论输入框 -->
    <view class="comment-input-section">
      <input 
        v-model="commentContent"
        placeholder="发表评论..."
        class="comment-input"
        maxlength="500"
        @focus="onCommentFocus"
        @blur="onCommentBlur"
      />
      <view 
        class="send-btn"
        :class="{ 'active': commentContent.trim() }"
        @click="sendComment"
      >
        发送
      </view>
    </view>

    <!-- 加载中 -->
    <view v-if="loading" class="page-loading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js'

export default {
  data() {
    return {
      postId: '',
      post: null,
      commentList: [],
      commentContent: '',
      loading: true,
      commentLoading: false,
      commentPage: 1,
      commentPageSize: 20,
      commentNoMore: false
    }
  },
  onLoad(options) {
    if (options.id) {
      this.postId = options.id
      this.loadPostDetail()
      this.loadComments(true)
    }
  },
  methods: {
    // 加载帖子详情
    async loadPostDetail() {
      this.loading = true
      
      try {
        const response = await api.request({
          url: `/exposure/posts/${this.postId}`,
          method: 'GET'
        })
        if (response.success) {
          this.post = response.data.post
        } else {
          uni.showToast({
            title: '帖子不存在',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载评论列表
    async loadComments(refresh = false) {
      if (this.commentLoading) return
      
      this.commentLoading = true
      
      try {
        const page = refresh ? 1 : this.commentPage
        const response = await api.request({
          url: `/exposure/posts/${this.postId}/comments?page=${page}&pageSize=${this.commentPageSize}`,
          method: 'GET'
        })
        
        if (response.success) {
          const { comments, pagination } = response.data
          
          if (refresh) {
            this.commentList = comments
            this.commentPage = 1
            this.commentNoMore = false
          } else {
            this.commentList = [...this.commentList, ...comments]
          }
          
          this.commentPage = pagination.current_page + 1
          this.commentNoMore = pagination.current_page >= pagination.total_pages
        }
      } catch (error) {
        uni.showToast({
          title: '评论加载失败',
          icon: 'none'
        })
      } finally {
        this.commentLoading = false
      }
    },
    
    // 加载更多评论
    loadMoreComments() {
      if (!this.commentNoMore && !this.commentLoading) {
        this.loadComments()
      }
    },
    
    // 点赞/取消点赞
    async toggleLike() {
      if (!this.post) return
      
      try {
        const response = await api.request({
          url: `/exposure/posts/${this.postId}/like`,
          method: 'POST'
        })
        if (response.success) {
          this.post.is_liked = response.data.liked
          this.post.like_count += response.data.liked ? 1 : -1
        }
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    // 发送评论
    async sendComment() {
      if (!this.commentContent.trim()) return
      
      try {
        const response = await api.request({
          url: `/exposure/posts/${this.postId}/comments`,
          method: 'POST',
          data: {
            content: this.commentContent.trim()
          }
        })
        
        if (response.success) {
          // 添加评论到列表顶部
          this.commentList.unshift(response.data.comment)
          // 更新评论数量
          if (this.post) {
            this.post.comment_count += 1
          }
          // 清空输入框
          this.commentContent = ''
          
          uni.showToast({
            title: '评论成功',
            icon: 'success'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '评论失败',
          icon: 'none'
        })
      }
    },
    
    // 分享帖子
    async sharePost() {
      if (!this.post) return
      
      try {
        // 记录分享统计
        await api.request({
          url: `/exposure/posts/${this.postId}/share`,
          method: 'POST'
        })
        
        // 更新分享配置
        this.setShareConfig({
          title: '曝光台 - ' + (this.post.content.slice(0, 30) + (this.post.content.length > 30 ? '...' : '')),
          path: `/pages/exposure/detail?id=${this.postId}`,
          imageUrl: this.post.images?.[0] ? this.getFullImageUrl(this.post.images[0]) : '/static/logo.png'
        })
        
        // 微信小程序中触发分享需要调用系统分享功能
        // #ifdef MP-WEIXIN
        this.triggerShare()
        // #endif
        
        // #ifdef APP-PLUS
        uni.share({
          provider: 'weixin',
          scene: 'WXSceneSession',
          type: 0,
          href: `/pages/exposure/detail?id=${this.postId}`,
          title: '曝光台 - ' + (this.post.content.slice(0, 30) + '...'),
          summary: this.post.content,
          success: () => {
            this.post.share_count += 1
          }
        })
        // #endif
        
      } catch (error) {
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    },
    
    // 聚焦评论输入框
    focusCommentInput() {
      // 这里可以滚动到底部并聚焦输入框
    },
    
    // 评论输入框聚焦
    onCommentFocus() {
      // 可以在这里做一些UI调整
    },
    
    // 评论输入框失焦
    onCommentBlur() {
      // 可以在这里做一些UI调整
    },
    
    // 预览图片
    previewImage(images, current) {
      const urls = images.map(img => this.getFullImageUrl(img))
      uni.previewImage({
        urls,
        current
      })
    },
    
    // 获取完整图片URL
    getFullImageUrl(imagePath) {
      if (!imagePath) return ''
      if (imagePath.startsWith('http')) return imagePath
      return api.getBaseURL().replace('/api/v1', '') + imagePath
    },
    
    // 根据图片数量获取样式类名
    getImageClass(count) {
      if (count === 1) return 'single'
      if (count === 2) return 'double'
      if (count === 4) return 'four'
      return 'multiple'
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '刚刚'
      
      const time = new Date(timeStr)
      if (isNaN(time.getTime())) {
        return '刚刚'
      }
      
      const now = new Date()
      const diff = now - time
      
      if (diff < 60 * 1000) {
        return '刚刚'
      } else if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前'
      } else if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
      } else if (diff < 7 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前'
      } else {
        return time.toLocaleDateString()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.post-detail {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
  }
  
  .user-detail {
    .nickname {
      display: block;
      font-size: 30rpx;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .time {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.content {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.images-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.post-image {
  border-radius: 8rpx;
  
  &.single {
    width: 400rpx;
    height: 300rpx;
  }
  
  &.double {
    width: calc(50% - 5rpx);
    height: 200rpx;
  }
  
  &.four {
    width: calc(50% - 5rpx);
    height: 150rpx;
  }
  
  &.multiple {
    width: calc(33.33% - 7rpx);
    height: 150rpx;
  }
}

.actions {
  display: flex;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .action-item {
    display: flex;
    align-items: center;
    margin-right: 60rpx;
    color: #666;
    font-size: 28rpx;
    
    .action-icon {
      margin-right: 8rpx;
      font-size: 32rpx;
      
      &.liked {
        filter: brightness(1.2) saturate(1.5);
      }
    }
  }
}

.comments-section {
  background-color: #fff;
  
  .section-title {
    padding: 30rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.comment-list {
  max-height: 600rpx;
}

.comment-item {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #f8f8f8;
  
  .comment-avatar {
    width: 60rpx;
    height: 60rpx;
    border-radius: 30rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
  }
  
  .comment-content {
    flex: 1;
    
    .comment-user {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 8rpx;
    }
    
    .comment-text {
      font-size: 30rpx;
      color: #333;
      line-height: 1.5;
      margin-bottom: 8rpx;
    }
    
    .comment-time {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.comment-input-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  
  .comment-input {
    flex: 1;
    padding: 16rpx 24rpx;
    background-color: #f5f5f5;
    border-radius: 40rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
  }
  
  .send-btn {
    padding: 16rpx 32rpx;
    background-color: #ddd;
    color: #999;
    border-radius: 40rpx;
    font-size: 28rpx;
    
    &.active {
      background-color: #007AFF;
      color: #fff;
    }
  }
}

.loading, .no-more, .empty, .page-loading {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.page-loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>